﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System.Text;
using System.Text.RegularExpressions;

namespace DNA.Mvc
{
    /// <summary>
    /// Present the observer class to send the email to user when UserRegistedEvent trigger.
    /// </summary>
    public class UserRegistedEventObserver : TemplatedMailEventObserver<UserRegistedEvent>
    {
        private readonly Regex UsernameRegex = new Regex("\\{username\\}", RegexOptions.Compiled);
        private readonly Regex PasswordRegex = new Regex("\\{password\\}", RegexOptions.Compiled);
        private string subject = "User registered information";

        /// <summary>
        /// Get/Sets the email subject
        /// </summary>
        public override string Subject
        {
            get { return subject; }
            set { subject = value; }
        }

        protected override void OnFormatHtmlBody(UserRegistedEvent e, ref string html)
        {
            html = UsernameRegex.Replace(html, e.UserName);
            html = PasswordRegex.Replace(html, e.Password);
        }

        protected override void OnFormatTextBody(UserRegistedEvent e, ref string text)
        {
            var bodyText = new StringBuilder();
            bodyText.Append("Username:")
                .AppendLine(e.UserName)
                .Append("Password:")
                .AppendLine(e.Password);
            text = bodyText.ToString();
        }

        protected override string GetDestinationAddress(UserRegistedEvent e)
        {
            return e.Email;
        }
    }
}
